<?php
/*
 * @Date: 2024-03-21 16:26:48
 * @LastEditors: 搬铁的码农 dong2406@126.com
 * @LastEditTime: 2024-04-26 23:32:49
 * 
 * 数据库备份操作
 */

namespace Ldy\Controller;

use Ldy\Controller\BaseAdmin;
use Ldy\Lib\Grid;
use Ldy\Lib\Form;
use Ldy\Lib\Show;
use Ldy\Models\SysBackup;
use Ldy\Lib\DataBackup;
use support\Request;

class BackupData extends BaseAdmin
{
    protected $title = '备份';

    protected $formSuccessText = '备份成功！';


    public function getBackupStatus(){
        $backup = new DataBackup();
        $res = $backup->getLockData();

        return $this->successJson($res);
    }

    /**
     * 还原数据备份
     * {"GET":"还原数据备份"}
     * @param Request $request
     * @param Int $id
     * @return void
     */
    public function restore(Request $request, Int $id){

        $backup = new DataBackup();
        $res = $backup->setTimeout(0)->restore($id);
        if($res === false) return $this->errorJson($backup->getError());

        return $this->successJson($res);
    }

    public function getRestoreStatus(){
        $lockFilePath = base_path() . DIRECTORY_SEPARATOR  .'backup_databases' .DIRECTORY_SEPARATOR.'backup.lock';
        
        if(!file_exists($lockFilePath)) return $this->successJson(false);
        $lockDataStr = file_get_contents($lockFilePath);
        
        $lockData = json_decode($lockDataStr, true);

        return $this->successJson($lockData);
    }

    protected function grid()
    {

        $dataModel = new SysBackup();
        $grid = new Grid($dataModel);

        $grid->model()->order('create_time', 'desc');

        $grid->quickSearch(['id' => "ID", 'folder' => '文件名']);

        $grid->column("id", "#")->width('100');
        $grid->column("folder", "文件名");
        $grid->column("desc", "备份注释");
        $grid->column("size", "大小")->suffixText("mb");
        $grid->column("tables", "备份表")->hide();
        $grid->column("status", "状态")->using($dataModel->status_array);

        $grid->column("create_time", "备份时间");


        return $grid;
    }

    protected function detail($id)
    {
        $show = new Show(SysBackup::find($id));

        $show->field("id", "ID");
        $show->field("folder", "文件名");
        $show->field("size", '大小')->suffixText('MB');
        $show->field("tables", "备份表")->tag('',',')->attrs(["size"=>"medium","effect"=>"dark"]);
        $show->field('create_time', '备份时间');

        return $show;
    }

    protected function form()
    {

        $form = new Form(new SysBackup());
        $model = $form->model();
        $form->textarea('desc', '备份注释');

        $tables = $model->getTablesOption(['qs_sys_backup']);
        $form->checkbox('tables', '数据表')->options($tables['option'])->value($tables['value']);
        
        $form->saving(function (Form $form) {
            $backup = new DataBackup();
            if($backup->isLock()) return '数据库正在备份中，请不要重复提交！';
        });

        $form->saved(function (Form $form) {

            $model = $form->model();
            $id = $model->id;

            $tables = $model->tables;
            $tablesArray = empty($tables) ? []:$tables;
            if(!is_array($tables)) $tablesArray = explode(',',$tables);
  
            $backup = new DataBackup();
            $size = $backup->getDatabasesSize();
            $FolderName = $backup->getBackupFolderName();

            $model->update(["folder"=>$FolderName, "size"=>$size], ["id"=>$id]);

            $res = $backup->setTables($tablesArray)->setTimeout(0)->dump();

            if($res === false) return '数据库正在备份中，请不要重复提交！';

            $model->update(["status"=>1, "sql_num"=>$res['sql_num']], ["id"=>$id]);

        });

        return $form;
    }

    /**
     * 删除管理员
     * {"DELETE":"删除{title}"}
     * @param Request $request
     * @param Int $id
     * @return void
     */
    public function destroy(Request $request, Int $id){
        
        if(empty($id)) return $this->errorJson('非法操作！');

        $info = SysBackup::where('id', $id)->find();

        if($info->isEmpty()) return $this->errorJson("删除失败，数据不存在！");

        $folder = DataBackup::instance()->getBasePath($info->folder);

        del_dir($folder);

        SysBackup::destroy($id);

        return $this->successJson($id,'删除成功！');
    }
}
